import { destroySdk } from '@/utils/im';
import Taro from '@tarojs/taro';
/**
 * 获取url参数
 * @param currentPage
 */
export const getQueryString = (options: unknown) => {
  if (options) {
    const queryString = Object.keys(options)
      .map((key) => `${key}=${options[key]}`)
      .join('&');
    return queryString;
  }
  return '';
};

/**
 * 获取当前页url
 */
export const getCurrentPageUrl = () => {
  const pages = Taro.getCurrentPages();

  const currentPage = pages[pages.length - 1];

  let url = '';

  if (currentPage.options) {
    url = `${currentPage.route}?${getQueryString(currentPage.options)}`;
  } else {
    url = `${currentPage.route}`;
  }

  return url;
};

/**
 * 跳转登录页
 */
export const pageToLogin = () => {
  const path = getCurrentPageUrl();
  Taro.clearStorageSync()
  destroySdk()
  if (!path?.includes('login')) {
    const redirect = path ? `/${path}` : '/pages/login/index';

    Taro.redirectTo({
      url: `/pages/login/index?redirect=${encodeURIComponent(redirect)}`,
    });
  }
};

/**
 * 页面跳转适配器
 * @param options 跳转参数
 * options.url 跳转地址
 * options.type 跳转类型，可选 'redirect' | 'navigate'，默认自动判断
 */
export function redirectToAdapter(options: { url: string; type?: 'redirect' | 'navigate' }) {
  // tabBar 页面列表，可根据实际项目配置
  const tabBarPages = ['/pages/home/index', '/pages/order/index', '/pages/user/index'];
  const isTabBar = tabBarPages.some((page) => options.url.startsWith(page));
  if (isTabBar) {
    Taro.switchTab({ url: options.url });
  } else if (options.type === 'redirect') {
    Taro.redirectTo({ url: options.url });
  } else {
    Taro.navigateTo({ url: options.url });
  }
}
